package com.allenkerr;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

/**
 * @author 小柯
 * @date 2018/3/20
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTest2 {

  @Autowired
  private RedisTemplate redisTemplate;

  public static final String REDIS_KEY = "queue-list-2";

  @Test
  public void test1() {
    final RedisConnectionFactory connectionFactory = redisTemplate.getConnectionFactory();
    final RedisConnection redisConnection = RedisConnectionUtils.getConnection(connectionFactory);
    final byte[] rawKey = redisTemplate.getKeySerializer().serialize(REDIS_KEY);

    while (true) {
      try {
        List<byte[]> results = redisConnection.bLPop(0, rawKey);
        if (CollectionUtils.isEmpty(results)) {
          continue;
        }
        String value = (String) redisTemplate.getValueSerializer().deserialize(results.get(1));
        if (value != null) {
          //do something
          System.out.println("value = " + value);
          Thread.sleep(200);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  @Test
  public void test2() {
    final ListOperations<String, String> listOperations = redisTemplate.opsForList();
    for (int i = 0; i < 200; i++) {
      listOperations.rightPush(REDIS_KEY, "test_" + i);
    }
  }

}
